package models

import "log"

type JobInterface interface {
	DoGet() error
}

type Worker struct {
	JobQueue chan JobInterface
}

func NewWorker() Worker {
	return Worker{JobQueue: make(chan JobInterface)}
}

func (w Worker) Run(wq chan chan JobInterface) {
	go func() {
		for {
			wq <- w.JobQueue
			select {
			case job := <-w.JobQueue:
				job.DoGet()
			}
		}
	}()
}

// ---------------------------------------------------------

type WorkerPool struct {
	workerlen   int
	JobQueue    chan JobInterface
	WorkerQueue chan chan JobInterface
}

func NewWorkerPool(workerlen, joblen int) *WorkerPool {
	return &WorkerPool{
		workerlen:   workerlen,
		JobQueue:    make(chan JobInterface, joblen),
		WorkerQueue: make(chan chan JobInterface, workerlen),
	}
}

func (wp *WorkerPool) Start() {
	log.Println("初始化worker")
	//初始化worker
	for i := 0; i < wp.workerlen; i++ {
		worker := NewWorker()
		worker.Run(wp.WorkerQueue)
	}
	// 循环获取可用的worker,往worker中写job
	go func() {
		for {
			select {
			case job := <-wp.JobQueue:
				worker := <-wp.WorkerQueue
				worker <- job
			}
		}
	}()
}

func NewPool() *WorkerPool {
	workernum := 100 * 100 * 1
	jobnum := 100 * 100 * 10
	// debug.SetMaxThreads(num + 1000) //设置最大线程数
	// 注册工作池，传入任务
	// 参数1 worker并发个数
	p := NewWorkerPool(workernum, jobnum)
	p.Start()
	return p
}
func Runpool(p *WorkerPool, i int) {
	sc := &Score{Num: i}
	p.JobQueue <- sc

	static := &Static{Num: i}
	p.JobQueue <- static
	// datanum := 100 * 100 * 100 * 100
	// go func() {
	// 	for i := 1; i <= datanum; i++ {
	// 		sc := &Score{Num: i}
	// 		p.JobQueue <- sc
	// 	}
	// }()

	// for {
	// 	fmt.Println("runtime.NumGoroutine() :", runtime.NumGoroutine())
	// 	time.Sleep(2 * time.Second)
	// }
}
